package com.cuile.littletools.scan

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.navigation.fragment.NavHostFragment
import com.cuile.littletools.*
import com.cuile.littletools.LittleToolsContacts.LOCAL_SCANE_RESULT
import com.cuile.littletools.LittleToolsContacts.REQUEST_ALBUM_IMAGE

import com.google.zxing.client.android.Intents
import com.journeyapps.barcodescanner.CaptureManager
import com.journeyapps.barcodescanner.DecoratedBarcodeView
import kotlinx.android.synthetic.main.activity_my_capture.*


@Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
/**
 * Created by cuile on 18-10-29.
 *
 */
class MyCaptureActivity: BaseActivity(), DecoratedBarcodeView.TorchListener {


    private lateinit var capture: CaptureManager

    override fun initCreateActivity(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_my_capture)

        initWindow()

        setActionBar(captureToolbar)
        actionBar.setDisplayHomeAsUpEnabled(true)
        captureToolbar.setNavigationOnClickListener { finish() }
        captureToolbar.inflateMenu(R.menu.menu_qr_scan)
        captureToolbar.setOnMenuItemClickListener {
            when(it.itemId){
                R.id.action_menu_from_album -> {
                    getAlbumImg()
                }
                else -> {}
            }
            false
        }

        capture = CaptureManager(this, barcodeScanner)
        capture.initializeFromIntent(intent, savedInstanceState)
        capture.decode()

        captureLightRadioButton.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                barcodeScanner.setTorchOn()
            } else {
                barcodeScanner.setTorchOff()
            }
        }
    }



    private fun getAlbumImg() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
                .addCategory(Intent.CATEGORY_OPENABLE)
                .setType("image/*")

        startActivityForResult(intent, REQUEST_ALBUM_IMAGE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            when(requestCode) {
                REQUEST_ALBUM_IMAGE -> {
                    val imgUri = data.data
                    val qrCode = scanImg(imgUri)
                    if (qrCode == null) {
                        Toast.makeText(applicationContext, "识别失败!", Toast.LENGTH_LONG).show()
                    } else {

//                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("www.cuile.littletool/scanresult")).apply {
//                            putExtra(Intents.Scan.RESULT, qrCode)
//                        }
//                        startActivity(intent)
                        setResult(LOCAL_SCANE_RESULT, Intent().putExtra(Intents.Scan.RESULT, qrCode))
                        finish()
                    }
                }
                else -> {}
            }
        }
    }

    private fun scanImg(imgUri: Uri?): String? {
        val bitmap = MediaStore.Images.Media.getBitmap(applicationContext.contentResolver, imgUri).getSmallerBitmap()
        val bitmapWidth = bitmap.width
        val bitmapHeight = bitmap.height
        val qrCode = bitmap.getBitmapYUVBytes().decodeYUVByZxing(bitmapWidth, bitmapHeight)
        Log.i("CaptureAct", "Scanning result is $qrCode!")
        return qrCode
    }


    /**
     * 初始化窗口
     */
    private fun initWindow() {
        val layoutParams = window.attributes
        layoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN or layoutParams.flags

    }


    override fun onResume() {
        super.onResume()
        capture.onResume()
    }

    override fun onPause() {
        super.onPause()
        capture.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        capture.onDestroy()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        capture.onSaveInstanceState(outState)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        capture.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return barcodeScanner.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event)
    }

    override fun onTorchOn() {
        captureLightRadioButton.isChecked = true
    }

    override fun onTorchOff() {
        captureLightRadioButton.isChecked = false
    }

}